<?php
include_once 'application/controllers/AbstractController.php';
include_once 'application/models/Utilisateur.php';
require_once('Zend/Mail.php');

class AuthController extends AbstractController
{
	function init()
	{
		// init
	}
	
	function indexAction()
	{
		HttpUtil::do400();
	}

	function loginAction()
	{
		$inactive = '';

		if (!$this->_request->isGet()) {
			HttpUtil::do405();
		}else{ 
			// collect the data from the user
			Zend_Loader::loadClass('Zend_Filter_StripTags');
			$f = new Zend_Filter_StripTags();
			$username = $f->filter($this->_request->getParam('login'));
			$password = $f->filter($this->_request->getParam('password'));

			if (empty($username)) {
				HttpUtil::do400('username_missing');
			} else {
				// setup Zend_Auth adapter for a database table
				Zend_Loader::loadClass('Zend_Auth_Adapter_DbTable');
				$dbAdapter = Zend_Registry::get('dbAdapter');
				$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
				$authAdapter->setTableName('Utilisateur');
				$authAdapter->setIdentityColumn('login');
				$authAdapter->setCredentialColumn('digest_password');

				// Set the input credential values to authenticate against
				$authAdapter->setIdentity($username);
				$authAdapter->setCredential(sha1($password . Zend_Registry::getInstance()->get('config')->salt));

				// do the authentication
				$auth = Zend_Auth::getInstance();
				$result = $auth->authenticate($authAdapter);

				
				//if valid member found, store the information in session memory.
				if ($result->isValid()) {
					$data = $authAdapter->getResultRowObject(null, 'password');
					$auth->getStorage()->write($data);
					$userdata = $auth->getIdentity();
					if($userdata->status == 0){
						$auth->clearIdentity();
						HttpUtil::do401('desactivated_account');
						$inactive = 'True';
					}
				} else {
					// failure: clear database row from session
					HttpUtil::do401();
				}
			} //end username was populated
		}
	}

	function logoutAction()
	{
		Zend_Auth::getInstance()->clearIdentity();
	}

	function recoveryAction()
	{
		$email = $this->getRequest()->getParam('email');
		$isValid = TypeChecker::validate(array(
			array('data' => $email, 'type' => TypeChecker::$_EMAIL_TYPE, 'name' => 'email')
		));
		if ($isValid !== true) {
			HttpUtil::do400('validation', $isValid);
		}
		
		// check if that email is registered
	    $table = new Utilisateur();
		
		$where = $table->getAdapter()->quoteInto('email = ?', $email);
	    $userRows = $table->fetchAll($where);
		
	    if (!isset($userRows[0])) {
	    	return;
	    }
	    $user = $userRows[0];
		
		// generate token
	    $token = md5(sha1(time().'SALT_^##@\è'));
		try {
			$data = array(
				're_init_token' => $token
			);
			 
			$where = $table->getAdapter()->quoteInto('id = ?', $user['id']);

			$numberOfRows = $table->update($data, $where);
		} catch (Exception $exception) {
			HttpUtil::do400('error');
		}
	    		
	    if ($numberOfRows < 1) {
	    	// utilisateur inexistant : 200 (impossible normalement)
	    	return;
	    }
		
		// send mail
		$config = Zend_Registry::getInstance()->get('config');
		MailUtil::sendMail(
			'Réinitialisation de votre mot de passe Pictolemmes', 
		
			"Bonjour,\n".
			"\n".
			"Vous recevez ce message car vous avez signalé avoir oublié votre mot de passe. Pour des raisons de sécurité, nous ne pouvons vous le transmettre, vous devez le réinitialiser en cliquant sur le lien ci-dessous :\n".
			"\n".
			$config->site->baseurl."/auth/passwordrecov?i=".$user['id'].'&t='.$token."\n".
			"\n".
			"Cordialement,\n".
			"L'équipe Pictolemmes\n".
			"\n".
			"\n".
			"Si vous n'êtes pas à l'origine de cette demande, veuillez ne pas en tenir compte.",
			
			$email
		);
	}
	

	function passwordrecovAction()
	{
		$layout = Zend_Layout::getMvcInstance();
		$layout->disableLayout();

		$password = $this->getRequest()->getParam('password_r');
		if (isset($password) && $password != "") {
			$id = $this->getRequest()->getParam('i');
			$token = $this->getRequest()->getParam('t');

			$data = array(
				're_init_token' => null,
				'digest_password' => sha1($password . Zend_Registry::getInstance()->get('config')->salt)
			);

			$table = new Utilisateur();
			$where = array();
			$where[] = $table->getAdapter()->quoteInto('id = ?', $id);
			$where[] = $table->getAdapter()->quoteInto('re_init_token = ?', $token);
			$where[] = $table->getAdapter()->quoteInto('re_init_token IS NOT NULL', $token);

			try {
				$numberOfRows = $table->update($data, $where);
			}catch (Exception $e) {
				return;
			}

			if ($numberOfRows < 1) {
				return;
			} else {
				
				// get user
	    		$table = new Utilisateur();
				try {
					$where = $table->getAdapter()->quoteInto('id = ?', $id);
		
					$userRows = $table->fetchAll($where);
					
					$email = $userRows[0]->email;
				} catch (Exception $exception) {
				}
				
				// send mail
				MailUtil::sendMail(
					'Réinitialisation de votre mot de passe Pictolemmes', 
				
					"Bonjour,\n".
					"\n".
					"Votre mot de passe a bien été réinitialisé.\n".
					"\n".
					"Cordialement,\n".
					"L'équipe Pictolemmes\n",
					
					$email
				);
								
				// write page
				echo "Merci. Vous allez recevoir un mail de confirmation.<br><br>L'équipe Pictolemmes";
				exit;
			}
		}
	}
	
}